package com.tieto.user.service;

import java.util.List;

import javax.jws.WebService;

import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Iterables;
import com.tieto.file.model.File;
import com.tieto.file.repository.FileRepository;
import com.tieto.user.model.User;
import com.tieto.user.repository.UserRepository;

/**
 * Implementation of UserService. endpointInterface and serviceName are probably
 * unneccessary.
 */
@Transactional
@WebService(endpointInterface = "com.tieto.user.service.UserService", serviceName = "userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private FileRepository fileRepository;
    private static final User[] EMPTY_USER_ARRAY = new User[0];

    @Override
    public User[] findAll() {
        Iterable<User> users = userRepository.findAll();
        // return empty list instead of null
        if (Iterables.isEmpty(users)) {
            return EMPTY_USER_ARRAY;
        } else {
            return Iterables.toArray(users, User.class);
        }
    }

    @Override
    public User create(User user) {
        Validate.notNull(user, "Tried to create null user.");
        Validate.notBlank(user.getUsername(), "Username must not be blank.");
        Validate.isTrue(userRepository.findByUsername(user.getUsername()) == null, "User already exists: {}",
                user.getUsername());
        return userRepository.save(user);
    }

    @Override
    public User update(User user) {
        User databaseUser = userRepository.findByUsername(user.getUsername());
        if (databaseUser != null) {
            databaseUser.setEmail(user.getEmail());
            databaseUser.setPassword(user.getPassword());
            databaseUser.setRole(user.getRole());
            databaseUser.setUsername(user.getUsername());
            return userRepository.save(databaseUser);
        }
        return null;
    }

    @Override
    // TODO change to id
    public User findOne(String username) {
        return userRepository.findByUsername(username);
    }

    @Override
    public boolean exists(String username) {
        return userRepository.findByUsername(username) != null;
    }

    @Override
    public void delete(String username) {
        User user = userRepository.findByUsername(username);
        if (user == null) {
            return;
        }
        List<File> files = fileRepository.findAllByOwner(user);
        fileRepository.delete(files);
        userRepository.delete(user.getId());
    }

    @Override
    public long count() {
        return userRepository.count();
    }

    @Override
    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }
}
